﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace IceDog.Practice.WinForm.IceDogSocket
{
    class FormSocketMainCore
    {
        private IPAddress _IP;
        private int _port;
        private Socket _server;
        private Dictionary<string, Socket> _sockeDictServer;
        private Dictionary<string, Socket> _sockeDictClient;

        public IPAddress IP
        {
            get
            {
                return _IP;
            }
        }

        public int Port
        {
            get
            {
                return _port;
            }
        }

        public Socket Server
        {
            get { return _server; }
        }

        public Dictionary<string, Socket> SockeDictServer
        {
            get
            {
                return _sockeDictServer;
            }
        }

        public Dictionary<string, Socket> SockeDictClient
        {
            get
            {
                return _sockeDictClient;
            }
        }

        public FormSocketMainCore()
        {
            this._sockeDictServer = new Dictionary<string, Socket>();
            this._sockeDictClient = new Dictionary<string, Socket>();
            this._server = GetTCPSocket();
        }

        private Socket GetTCPSocket()
        {
            return new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }
        
        public void SetIPAndPort(string IP, int Port)
        {
            this._IP =IPAddress.Parse(IP);
            this._port = Port;
        }

        public void StartServerListen()
        {
            this._server.Bind(new IPEndPoint(this._IP,this._port));
            //同一个时间点过来10个客户端，排队
            this._server.Listen(10);
        }

        public void StartClientConnect(Socket client)
        {
            client.Connect(new IPEndPoint(this._IP, this._port));
            this._sockeDictClient.Add(client.LocalEndPoint.ToString(), client);
        }
        public Socket GetAcceptSocket()
        {
            //会进入监听状态(即后续代码会暂停执行直到有客户端socket连接)
            var accept = this._server.Accept();
            //存储与当前客户端访问的socket进行交互的服务端socket
            this._sockeDictServer.Add(accept.RemoteEndPoint.ToString(),accept);
            return accept;
        }

        public Socket GetClientSocket()
        {
            return GetTCPSocket();
        }
    }
}
